﻿//////////////////////////////////////////////////////////////////
//
// Program.cs
//
// Copyright (c) 2012 Dan Pike. All rights reserved
//
// Refer to license.txt for any license restrictions.
// 
using Logger4Net;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;

namespace Sally
{
   static class Program
   {
      public static Logger logger = new Logger(typeof(Program));
      public static Configuration config;
      public static Config.Sally settings;

      //////////////////////////////////////////////////////////////////////////
      //
      private static bool loadConfiguration()
      {
         try
         {
            config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            settings = config.GetSection(Config.Sally.CONFIG_SECTION) as Config.Sally;
            if (null == settings)
            {
               settings = new Config.Sally();
               config.Sections.Add(Config.Sally.CONFIG_SECTION, settings);
               config.Save(ConfigurationSaveMode.Full);
            }
            return true;
         }
         catch (System.Exception ex)
         {
            logger.exception(ex);
         }
         return false;
      }

      /// <summary>
      /// The main entry point for the application.
      /// </summary>
      [STAThread]
      static void Main()
      {
         bool createdNew = false;
         try
         {
            using (EventWaitHandle duplicateDetector = new EventWaitHandle(true, EventResetMode.ManualReset,
               "5D26CF18-C808-4B5E-9A71-E161A2208A18", out createdNew))
            {
               if (!createdNew)
               {
                  MessageBox.Show(string.Concat(Application.ProductName, " is already running, this will now close"),
                     Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Stop);
               }
               else
               {
                  Application.EnableVisualStyles();
                  Application.SetCompatibleTextRenderingDefault(false);

                  logger.debugFormat("loading configuration");
                  if (!loadConfiguration())
                  {
                     MessageBox.Show(string.Concat(Application.ProductName, " failed to load configuration file"),
                        Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                     return;
                  }
                  Application.Run(new Main());

                  logger.debugFormat("saving configuration changes");
                  config.Save(ConfigurationSaveMode.Full);

                  // Copy it back up to prevent losing it when VS2010 overwrites it
                  if (config.FilePath.EndsWith(".vshost.exe.Config", StringComparison.CurrentCultureIgnoreCase))
                  {
                     string sourceFile = Path.Combine(
                        Path.GetDirectoryName(config.FilePath),
                        "..", "..", Application.ProductName,
                        "app.config"
                        );
                     if (File.Exists(sourceFile) && (0 == (File.GetAttributes(sourceFile) & FileAttributes.ReadOnly)))
                     {
                        File.Copy(config.FilePath, sourceFile, true);
                     }
                  }
               }
            }
         }
         catch (Exception ex)
         {
            // We didn't catch the exception
            MessageBox.Show(
               string.Concat(Application.ProductName, " threw an exception: ", ex.Message),
               Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Stop);
         }
         finally
         {
            logger.debugFormat("{0} is exiting", Application.ProductName);
         }
      }
   }
}
